/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    DeviceEventEmitter,
    Image,
    ListView,
    ScrollView,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
} from 'react-native';
import StyleUtils from "../../../res/styles/StyleUtils";
import Navigation from "../../../custom/Navigation";
import ModalListUtils from "../../../utils/ModalListUtils";
import ViewUtils from "../../../utils/ViewUtils";
import DateTimePicker from 'react-native-modal-datetime-picker';
import moment from 'moment';
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import IparInput from "../../../custom/IparInput";


export default class UserInformationEdit extends Component {
    constructor(props) {
        super(props);
        let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.genderArr = [I18n.t('default.male'), I18n.t('default.female'), I18n.t('default.secrecy')];
        this.state = {
            dataSource: ds.cloneWithRows(this.genderArr),
            modalDialog: false,
            genderIndex: '',
            dateHolder: '',
            isDateTimePickerVisible: false,
            firstName: '',
            middleName: '',
            familyName: '',
            idNumber: '',
        };

        this.iparNetwork = new IparNetwork();

    }

    componentWillUnmount() {
        this.iparNetwork = null;
    }


    /*编辑用户联系信息*/
    editUserInfo() {
        let userData = this.props.userData;
        let gender = userData ? userData.sex : '';
        let genderIndex = this.state.genderIndex;
        if (genderIndex === I18n.t('default.male')) {
            gender = 1;
        } else if (genderIndex === I18n.t('default.female')) {
            gender = 0;
        } else if (genderIndex === I18n.t('default.secrecy')) {
            gender = 2;
        }

        let _fristName = this.state.firstName ? this.state.firstName : userData && userData.first_name ? userData.first_name : '';
        let _middleName = this.state.middleName ? this.state.middleName : userData && userData.middle_name ? userData.middle_name : '';
        let _lastName = this.state.familyName ? this.state.familyName : userData && userData.last_name ? userData.last_name : '';
        let _birthDay = this.state.dateHolder ? this.state.dateHolder : userData && userData.birth_day ? userData.birth_day : '';
        let _idNumber = this.state.idNumber ? this.state.idNumber : userData && userData.id_number ? userData.id_number : '';

        let formData = new FormData();
        formData.append("user_id", userData.main_user_id);
        formData.append("first_name", _fristName || '');
        formData.append("middle_name", _middleName || '');
        formData.append("last_name", _lastName || '');
        formData.append("birth_day", _birthDay || '');
        formData.append("status", '4');
        formData.append("sex", gender || '');
        formData.append("id_number", _idNumber || '');

        this.iparNetwork.getPostFrom(SERVER_TYPE.admin + 'updateUserInfo', formData)
            .then((result) => {
                if (result.code === 200) {

                    userData.first_name = _fristName;
                    userData.middle_name = _middleName;
                    userData.last_name = _lastName;
                    userData.birth_day = _birthDay;
                    userData.sex = gender;
                    userData.id_number = _idNumber;

                    this.props.navigator.pop();
                    this.props.callback && this.props.callback(userData);
                    DeviceEventEmitter.emit('toast', I18n.t('default.success'));
                    DeviceEventEmitter.emit('upDateUserData', userData);
                } else {
                    this.props.navigator.popToTop();
                    DeviceEventEmitter.emit('loadUserData');
                }
                CommonUtils.dismissLoading();

            })
            .catch((error) => {
                CommonUtils.dismissLoading();
                console.log(error)
            })
    }

    /*显示日期输入框 */
    _showDateTimePicker = () => this.setState({isDateTimePickerVisible: true});
    /* 隐藏日期输入框*/
    _hideDateTimePicker = () => this.setState({isDateTimePickerVisible: false});
    /*获取日期输入框*/
    _handleDatePicked = (date) => {
        let DateFormat = moment(date).format("YYYY-MM-DD");
        this.setState({dateHolder: DateFormat});
        this._hideDateTimePicker();
    };

    /*用户信息btn 点击*/
    userInformationEdit() {
        // if (this.state.firstName.trim() === '') {
        //     DeviceEventEmitter.emit('toast', I18n.t('default.enterFirstName'))
        // }
        // else if (this.state.middleName.trim() === '') {
        //     DeviceEventEmitter.emit('toast', I18n.t('default.middleName'))
        // } else if (this.state.familyName.trim() === '') {
        //     DeviceEventEmitter.emit('toast', I18n.t('default.enterFamilyName'))
        // }
        // else {
        //
        // }

        CommonUtils.showLoading();
        this.editUserInfo();

    }


    render() {
        let userData = this.props.userData;
        let typePage;
        let gender = I18n.t('default.secrecy');
        if (userData) {
            if (userData.sex === 0) {
                gender = I18n.t('default.female');
            } else if (userData.sex === 1) {
                gender = I18n.t('default.male');
            }
        }


        // if (this.props.pageType === 0) {
        typePage = <View style={[StyleUtils.flex, {paddingBottom: 16}]}>
            <IparInput
                onChangeText={(name) => {
                    this.setState({firstName: name})
                }}
                placeholder={userData && userData.first_name ? userData.first_name : I18n.t('default.firstName')}/>

            {userData.country !== 'CN' ? <IparInput
                onChangeText={(name) => {
                    this.setState({middleName: name})
                }}
                placeholder={userData && userData.middle_name ? userData.middle_name : I18n.t('default.middleName')}/> : null}

            <IparInput
                onChangeText={(name) => {
                    this.setState({familyName: name})
                }}
                placeholder={userData && userData.last_name ? userData.last_name : I18n.t('default.familyName')}/>

            {ViewUtils.getButtunMenu(this.state.dateHolder ? this.state.dateHolder : userData && userData.birth_day ? userData.birth_day : I18n.t('default.dateOfBirth'), () => {
                this._showDateTimePicker()
            }, {marginTop: 16})}

            {ViewUtils.getButtunMenu(this.state.genderIndex ? this.state.genderIndex : gender ? gender : I18n.t('default.gender'), () => {
                this.setState({modalDialog: true})
            }, {marginTop: 16})}

            <IparInput
                onChangeText={(name) => {
                    this.setState({idNumber: name})
                }}
                placeholder={userData && userData.id_number ? userData.id_number : I18n.t('default.idNumber')}/>

            {ViewUtils.getButton(I18n.t('default.submit'), () => {
                this.userInformationEdit()
            }, {marginTop: 50})}
        </View>;

        return (
            <View style={[StyleUtils.flex, {backgroundColor: 'white'}]}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}
                />
                <ModalListUtils
                    onPress={(index) => {
                        this.setState({
                            genderIndex: this.genderArr[index],
                            modalDialog: false,

                        });
                    }}
                    visible={this.state.modalDialog}
                    dataSource={this.state.dataSource}
                    close={() =>
                        this.setState({
                            modalDialog: false,
                        })
                    }
                />

                <DateTimePicker
                    isVisible={this.state.isDateTimePickerVisible}
                    onConfirm={this._handleDatePicked}
                    onCancel={this._hideDateTimePicker}
                />
                <ScrollView style={StyleUtils.flex}>
                    <View style={{paddingLeft: 16, paddingRight: 16}}>
                        {ViewUtils.getTitleView(I18n.t('default.editProfile'), I18n.t('default.editYourAccount'))}
                        {typePage}
                    </View>
                </ScrollView>
            </View>
        );
    }


}

